package com.example.block_chain.config.filter;

import com.example.block_chain.domain.pojo.Admin;
import com.example.block_chain.domain.pojo.Student;
import com.example.block_chain.mapper.AdminMapper;
import com.example.block_chain.mapper.StudentMapper;
import com.example.block_chain.utils.Admin.AdminDetailsImpl;
import com.example.block_chain.utils.JwtUtil;
import com.example.block_chain.utils.student.StudentDetailsImpl;
import io.jsonwebtoken.Claims;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 验证这个jwttoken是否合法，如果合法，会把student提取到上下文当中
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Autowired
    private StudentMapper studentMapper;

    @Autowired
    private AdminMapper adminMapper;

    @Override
    protected void doFilterInternal(HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull FilterChain filterChain) throws ServletException, IOException {
        String token = request.getHeader("Authorization");

        if (!StringUtils.hasText(token) || !token.startsWith("Bearer ")) {
            filterChain.doFilter(request, response);
            return;
        }

        token = token.substring(7);

        String userid;
        try {
            Claims claims = JwtUtil.parseJWT(token);
            userid = claims.getSubject();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        Student student = null;
        Admin admin = null;
        UsernamePasswordAuthenticationToken authenticationToken = null;
        if(userid.startsWith("student")) {
            userid = userid.substring(7);
            student = studentMapper.selectById(Integer.parseInt(userid));
            StudentDetailsImpl loginStudent = new StudentDetailsImpl(student);
            authenticationToken = new UsernamePasswordAuthenticationToken(loginStudent, null, null);
        } else if(userid.startsWith("admin")) {
            userid = userid.substring(5);
            admin = adminMapper.selectById(Integer.parseInt(userid));
            AdminDetailsImpl loginAdmin = new AdminDetailsImpl(admin);
            authenticationToken = new UsernamePasswordAuthenticationToken(loginAdmin, null, null);
        }


        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        filterChain.doFilter(request, response);
    }
}